<template>
  <div class="app-container" id="newStrategy">
    <el-form ref="form" :model="form" label-width="80px" :rules="addRules">
      <el-form-item label="攻略标题">
        <el-input v-model="form.name" class="w500"></el-input>
      </el-form-item>
      <el-form-item label="攻略类别">
        <el-select v-model="form.type" placeholder="攻略类别">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="攻略地址">
        <el-button @click="dialogTableVisible = true">{{address}}</el-button>
      </el-form-item>
      <el-dialog title="选择地址" :visible.sync="dialogTableVisible" top="15vh">
        <div class="amap-page-container">
          <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
          <el-amap vid="amap" :center="center" :zoom="zoom" :plugin="plugin" class="amap-demo" :events="events">
            <el-amap-marker :position="MakerPosition"></el-amap-marker>
          </el-amap>
          <div class="toolbar">
            <br /> 地址：{{ address }}
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogTableVisible = false">确 定</el-button>
      </span>
      </el-dialog>
      <el-form-item label="封面图片">
        <el-upload class="cover-uploader" action="http://www.jiatingyigou.com:7001/upload/img" :show-file-list="false" :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="coverImageUrl" :src="coverImageUrl" class="cover">
          <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
      </el-form-item>
      <el-form-item label="攻略简介">
        <el-input type="textarea" v-model="form.describe" placeholder="请输入简介" class="w500"></el-input>
      </el-form-item>
      <el-form-item label="营业时间">
        <!-- <el-input v-model="form.sellTime" placeholder="请输入营业时间"></el-input> -->
        <el-time-select
          placeholder="起始时间"
          v-model="startSellTime"
          :picker-options="{
            start: '00:00',
            step: '00:15',
            end: '24:00'
          }">
        </el-time-select>
        <el-time-select
          placeholder="结束时间"
          v-model="endSellTime"
          :picker-options="{
            start: '00:15',
            step: '00:15',
            end: '24:00',
            minTime: startSellTime
          }">
        </el-time-select>
      </el-form-item>
      <el-form-item label="攻略内容">
        <div class="changeText">HTML模式
          <el-switch
            v-model="openCode"
            on-text=""
            off-text="">
          </el-switch>
        </div>
        <el-input v-if="openCode==true" type="textarea" v-model="form.content" class="w500"></el-input>
        <quill-editor v-else ref="myTextEditor"
                      class="w500"
                      v-model="form.content"
                      :options="editorOption"
                      @blur="onEditorBlur($event)"
                      @focus="onEditorFocus($event)"
                      @ready="onEditorReady($event)">
        </quill-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即发布</el-button>
        <el-button type="warning" @click="onSave">存为草稿</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="提示" :visible.sync="dialogAddressVisible" size="tiny">
      <span>请选择攻略地址</span>
      <span slot="footer" class="dialog-footer">
    <el-button  @click="dialogAddressVisible = false">取消</el-button>
    <el-button  @click="dialogAddressVisible = false" type="primary">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogSuccessVisible" size="tiny">
      <span>添加成功,是否跳转到首页？</span>
      <span slot="footer" class="dialog-footer">
    <el-button  @click="dialogSuccessVisible = false">取消</el-button>
    <el-button  @click="GoToIndex" type="primary">确 定</el-button>
  </span>
    </el-dialog>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogAvatarVisible" size="tiny">
      <span>请选择完善攻略信息</span>
      <span slot="footer" class="dialog-footer">
    <el-button  @click="dialogAvatarVisible = false">取消</el-button>
    <el-button  @click="dialogAvatarVisible = false" type="primary">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>
<script>
import { isvalidStrategyContent } from "@/utils/validate";
import {
  getStrategyById,
  updateStrategy,
  updateStrategyDetail,
  addNewStrategy,
  addStrategyDetail
} from "@/api/strategy";
import { getToken } from "@/utils/auth";
export default {
  data() {
    let self = this;
    const validateTitle = (rule, value, callback) => {
      if (!isvalidStrategyContent(value)) {
        callback(new Error("请输入正确的标题"));
      } else {
        callback();
      }
    };
    const validateDesc = (rule, value, callback) => {
      if (!isvalidStrategyContent(value)) {
        callback(new Error("请输入描述"));
      } else {
        callback();
      }
    };
    const validateContent = (rule, value, callback) => {
      if (!isvalidStrategyContent(value)) {
        callback(new Error("请输入内容"));
      } else {
        callback();
      }
    };
    return {
      updateId: 0,
      dialogSuccessVisible: false,
      dialogAddressVisible: false,
      dialogAvatarVisible: false,
      dialogTableVisible: false,
      strategyType: "view",
      zoom: 12,
      center: [121.59996, 31.197646],
      address: "选择地址",
      describe: "",
      adcode: "",
      position: "",
      searchOption: {
        city: "全国",
        citylimit: true
      },
      plugin: [
        {
          pName: "Geolocation",
          events: {
            init(o) {
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  console.log(result);
                  self.addressInfo.lng = result.position.lng;
                  self.addressInfo.lat = result.position.lat;
                  self.addressInfo.traffic = result.formattedAddress;
                  self.address = result.formattedAddress;
                  self.addressInfo.adcode = result.addressComponent.adcode;
                  self.addressInfo.position =
                    result.addressComponent.city +
                    "-" +
                    result.addressComponent.district;
                }
              });
            }
          }
        }
      ],
      events: {
        click(e) {
          let { lng, lat } = e.lnglat;
          self.addressInfo.lng = lng;
          self.addressInfo.lat = lat;
          self.MakerPosition = [e.lnglat.lng, e.lnglat.lat];
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                self.addressInfo.traffic = result.regeocode.formattedAddress;
                self.address = result.regeocode.formattedAddress;
                self.addressInfo.adcode =
                  result.regeocode.addressComponent.adcode;
                self.addressInfo.position =
                  result.regeocode.addressComponent.city +
                  "-" +
                  result.regeocode.addressComponent.district;
                self.$nextTick();
              }
            }
          });
        }
      },
      MakerPosition: [121.59996, 31.197646],
      lng: 0,
      lat: 0,
      openCode: false,
      startSellTime: "",
      endSellTime: "",
      typeOptions: [
        {
          value: "景点",
          label: "景点"
        },
        {
          value: "美食",
          label: "美食"
        },
        {
          value: "休闲娱乐",
          label: "休闲娱乐"
        },
        {
          value: "购物",
          label: "购物"
        }
      ],
      form: {
        name: "",
        type: "景点",
        describe: "",
        content: "<p>请输入攻略内容...</p>",
        strategyType: "",
        cover: "",
        sellTime: "",
        status: 1
      },
      addressInfo: {
        lat: "",
        lng: "",
        position: "",
        traffic: "",
        adcode: ""
      },
      coverImageUrl: "",
      addRules: {
        name: [{ required: true, trigger: "blur", validator: validateTitle }],
        describe: [
          { required: true, trigger: "blur", validator: validateDesc }
        ],
        content: [
          { required: true, trigger: "blur", validator: validateContent }
        ]
      },
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"],
            ["blockquote", "code-block"],
            [{ header: 1 }, { header: 2 }],
            [{ list: "ordered" }, { list: "bullet" }],
            [{ script: "sub" }, { script: "super" }],
            [{ indent: "-1" }, { indent: "+1" }],
            [{ direction: "rtl" }],
            [{ size: ["small", false, "large", "huge"] }],
            [{ header: [1, 2, 3, 4, 5, 6, false] }],
            [{ font: [] }],
            [{ color: [] }, { background: [] }],
            [{ align: [] }],
            ["clean"],
            ["image"]
          ],
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      }
    };
  },
  created() {
    let id = this.$route.query.id;
    if (id) {
      getStrategyById(id).then(res => {
        this.updateId = res.strategy.id;
        this.form.name = res.strategy.name;
        this.form.type = res.strategy.typeName;
        this.form.describe = res.strategy.describe;
        let sellTimeArr = res.strategy.sellTime.split("-");
        this.startSellTime = sellTimeArr[0];
        this.endSellTime = sellTimeArr[1];
        // this.form.sellTime = res.strategy.sellTime;
        this.form.cover = res.strategy.cover;
        this.form.content = res.detail.content;
        this.form.strategyType = res.strategy.type;
        this.addressInfo.lat = res.strategy.lat;
        this.addressInfo.lng = res.strategy.lng;
        this.addressInfo.position = res.strategy.position;
        this.addressInfo.adcode = res.strategy.address;
        this.addressInfo.traffic = res.strategy.traffic;
        this.coverImageUrl = res.strategy.cover;
        this.address = res.strategy.traffic;
      });
    }
  },
  methods: {
    onEditorBlur(editor) {
      // console.log('editor blur!', editor)
    },
    onEditorFocus(editor) {
      // console.log('editor focus!', editor)
    },
    onEditorReady(editor) {
      // console.log('editor ready!', editor)
    },
    onSave() {
      this.form.status = 0;
      this.onSubmit();
    },
    onSubmit() {
      this.form.sellTime = this.startSellTime + "-" + this.endSellTime;
      if (this.address == "选择地址") {
        this.dialogAddressVisible = true;
        return;
      }
      if (
        this.form.cover == "" ||
        this.form.name == "" ||
        this.form.desc == "" ||
        this.form.content == "" ||
        this.form.sellTime == ""
      ) {
        this.dialogAvatarVisible = true;
        return;
      }
      let strategyType = "";
      if (this.form.type == "景点") {
        strategyType = "view";
      } else if (this.form.type == "美食") {
        strategyType = "food";
      } else if (this.form.type == "休闲娱乐") {
        strategyType = "entertainment";
      } else if (this.form.type == "购物") {
        strategyType = "mall";
      }
      this.form.strategyType = strategyType;
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.updateId == 0) {
            let content = this.form;
            let address = this.addressInfo;
            content.u_id = getToken();
            content.type = content.type.trim();
            content.sellTime = content.sellTime.trim();
            content.name = content.name.trim();
            content.describe = content.describe.trim();
            content.cover = content.cover.trim();
            content.content = content.content.trim();
            addNewStrategy(content, address).then(res => {
              var discovery_id = res.discovery_id;
              addStrategyDetail(discovery_id, content.content).then(data => {
                if (data.status == 1) {
                  this.dialogSuccessVisible = true;
                  this.form = {};
                  this.addressInfo = {};
                  this.address = "选择地址";
                  this.coverImageUrl = "";
                }
              });
            });
          } else {
            let discovery_id = this.updateId;
            let content = this.form;
            let address = this.addressInfo;
            content.id = discovery_id;
            content.type = content.type.trim();
            content.sellTime = content.sellTime.trim();
            content.name = content.name.trim();
            content.describe = content.describe.trim();
            content.cover = content.cover.trim();
            updateStrategy(content, address);
            updateStrategyDetail(discovery_id, this.form.content).then(data => {
              if (data.status == 1) {
                this.dialogSuccessVisible = true;
                this.form = {};
                this.addressInfo = {};
                this.address = "选择地址";
                this.coverImageUrl = "";
              }
            });
          }
        } else {
          console.log("提交的数据不合法!!");
          return false;
        }
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    GoToIndex() {
      this.$router.push({ path: "/" });
    },
    handlePreview(file) {
      console.log(file);
    },
    handleAvatarSuccess(res, file) {
      this.coverImageUrl = URL.createObjectURL(file.raw);
      this.form.cover = "http://" + res.data.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传封面图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传封面图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    addMarker: function() {
      let lng = 121.5 + Math.round(Math.random() * 1000) / 10000;
      let lat = 31.197646 + Math.round(Math.random() * 500) / 10000;
      this.MakerPosition = [lng, lat];
    },
    onSearchResult(pois) {
      var self = this;
      let latSum = 0;
      let lngSum = 0;
    
      if (pois.length > 0) {
        pois.forEach(poi => {
          let { lng, lat } = poi;
          lngSum += lng;
          latSum += lat;
          this.MakerPosition = [poi.lng, poi.lat];
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([poi.lng, poi.lat], function(status, result) {
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                  self.addressInfo.lat = poi.lng
                    self.addressInfo.lag =poi.lng
                self.addressInfo.traffic = result.regeocode.formattedAddress;
                self.address = result.regeocode.formattedAddress;
                self.addressInfo.adcode =
                  result.regeocode.addressComponent.adcode;
                self.addressInfo.position =
                  result.regeocode.addressComponent.city +
                  "-" +
                  result.regeocode.addressComponent.district;
                self.$nextTick();
          
              }
            }
          });
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        };
        this.center = [center.lng, center.lat];
      }
    }
  }
};
</script>
<style>
.amap-demo {
  height: 300px;
}

.search-box {
  position: absolute;
  top: 25px;
  left: 20px;
}

#newStrategy .el-vue-search-box-container {
  position: absolute;
}

.amap-page-container {
  position: relative;
  height: 360px;
}

.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.cover-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.cover {
  width: 178px;
  height: 178px;
  display: block;
}
.w500 {
  width: 500px;
}
</style>